package com.cnzhy.stream;

import com.google.common.collect.Lists;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: zhaoyan5
 */
public class FlatMapTest {

    /**
     * flatMap使用嵌套list
     */
    @Test
    public void flatMapTest1() {
        List<List<Integer>> lists = new ArrayList<>();
        List<Integer> list = Lists.newArrayList();
        list.add(4444);
        list.add(1111);
        list.add(3333);
        list.add(2222);
        lists.add(list);
        lists.stream().flatMap(Collection::stream).forEach(System.out::println);
    }

    @Test
    public void flatMapTest2() {
        List<String> teamIndia = Arrays.asList("Virat", "Dhoni", "Jadeja");
        List<String> teamAustralia = Arrays.asList("Warner", "Watson", "Smith");
        List<String> teamEngland = Arrays.asList("Alex", "Bell", "Broad");
        List<String> teamNewZeland = Arrays.asList("Kane", "Nathan", "Vettori");
        List<String> teamSouthAfrica = Arrays.asList("AB", "Amla", "Faf");
        List<String> teamWestIndies = Arrays.asList("Sammy", "Gayle", "Narine");
        List<String> teamSriLanka = Arrays.asList("Mahela", "Sanga", "Dilshan");
        List<String> teamPakistan = Arrays.asList("Misbah", "Afridi", "Shehzad");
        List<List<String>> worldCup = new ArrayList<>();
        worldCup.add(teamIndia);
        worldCup.add(teamAustralia);
        worldCup.add(teamEngland);
        worldCup.add(teamNewZeland);
        worldCup.add(teamSouthAfrica);
        worldCup.add(teamWestIndies);
        worldCup.add(teamSriLanka);
        worldCup.add(teamPakistan);
        // java 之前的写法 , 双层for循环
        List<String> listOfAllPlayers = Lists.newArrayList();
        for (List<String> team : worldCup) {
            for (String name : team) {
                listOfAllPlayers.add(name);
            }
        }
        System.out.println("Players playing in world cup 2016 not using Java 8");
        System.out.println(listOfAllPlayers);
        // Now let's do this in Java 8 using FlatMap
        List<String> flatMapList = worldCup.stream().flatMap(pList -> pList.stream()).collect(Collectors.toList());
        System.out.println("List of all Players using Java 8");
        System.out.println(flatMapList);
    }

    @Test
    public void toListTest() {
        List<String> wordList = Arrays.asList("a", "b", "c", "d");
        List<String> collect = wordList.stream().map(String::toUpperCase).collect(Collectors.toList());
        System.out.println(collect);
    }

}
